package com.duke.javaagent.bytebuddy01;

import com.duke.javaagent.bytebuddy01.interceptor.SpringMVCInterceptor;
import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import java.security.ProtectionDomain;

/**
 * @author gjy
 * @create 2024-12-10 12:44 PM
 */
public class AgentTransformer implements AgentBuilder.Transformer {
    private static final String MAPPING_PERFIX = "org.springframework.web.bind.annotation";
    private static final String MAPPING_SUFFIX = "Mapping";
    @Override
    public DynamicType.Builder<?> transform(DynamicType.Builder<?> builder,
                                            TypeDescription typeDescription,
                                            ClassLoader classLoader,
                                            JavaModule javaModule,
                                            ProtectionDomain protectionDomain) {
        System.out.println("打印类的名字： "+ typeDescription.getActualName());
        DynamicType.Builder.MethodDefinition.ReceiverTypeDefinition<?> intercept = builder
                .method(
                        ElementMatchers.not(ElementMatchers.isStatic()).and(ElementMatchers.isAnnotatedWith(
                                ElementMatchers.nameStartsWith(MAPPING_PERFIX).and(ElementMatchers.nameEndsWith(MAPPING_SUFFIX))
                        ))
                ).intercept(MethodDelegation.to(new SpringMVCInterceptor()));
        return intercept;
    }
}
